import React, { useEffect, useState } from "react";
import { message } from "../utils/customMessage";
import CustomMessage from "./CustomMessage";

interface MessageItem {
  id: string;
  type: "success" | "error" | "warning" | "info";
  content: string;
  duration?: number;
}

const GlobalMessageProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [messages, setMessages] = useState<MessageItem[]>([]);

  useEffect(() => {
    const unsubscribe = message.subscribe((messageData) => {
      const id =
        Date.now().toString() + Math.random().toString(36).substr(2, 9);
      const newMessage: MessageItem = {
        id,
        ...messageData,
      };

      setMessages((prev) => [...prev, newMessage]);
    });

    return unsubscribe;
  }, []);

  const removeMessage = (id: string) => {
    setMessages((prev) => prev.filter((msg) => msg.id !== id));
  };

  return (
    <>
      {children}
      {messages.map((msg, index) => (
        <div
          key={msg.id}
          style={{
            position: "fixed",
            top: `${20 + index * 60}px`,
            right: "20px",
            zIndex: 9999 + index,
          }}
        >
          <CustomMessage
            type={msg.type}
            content={msg.content}
            duration={msg.duration}
            onClose={() => removeMessage(msg.id)}
          />
        </div>
      ))}
    </>
  );
};

export default GlobalMessageProvider;
